using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.customers;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.customers
{
    /// <summary>
    /// 修改客户命令处理器
    /// </summary>
    public class UpdateCustomerCommandHandler : IRequestHandler<UpdateCustomerCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Customer> _customerRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateCustomerCommandHandler> _logger;

        public UpdateCustomerCommandHandler(
            IBaseRepository<Customer> customerRepository,
            IMapper mapper,
            ILogger<UpdateCustomerCommandHandler> logger)
        {
            _customerRepository = customerRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理修改客户命令
        /// </summary>
        /// <param name="request">修改客户命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateCustomerCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始修改客户，ID: {CustomerId}, 名称: {CustomerName}", 
                    request.Id, request.Name);

                // 检查客户是否存在
                var existingCustomer = await _customerRepository.GetAll()
                    .FirstOrDefaultAsync(c => c.Id == request.Id && !c.IsDeleted, cancellationToken);

                if (existingCustomer == null)
                {
                    _logger.LogWarning("客户不存在或已被删除，ID: {CustomerId}", request.Id);
                    return ApiResult<bool>.Error("客户不存在或已被删除");
                }

                // 验证客户编号是否与其他客户重复（排除当前客户）
                var duplicateCodeCustomer = await _customerRepository.GetAll()
                    .FirstOrDefaultAsync(c => c.CustomerCode == request.CustomerCode 
                                             && c.Id != request.Id 
                                             && !c.IsDeleted, cancellationToken);

                if (duplicateCodeCustomer != null)
                {
                    _logger.LogWarning("客户编号已存在，ID: {CustomerId}, 编号: {CustomerCode}", 
                        request.Id, request.CustomerCode);
                    return ApiResult<bool>.Error("客户编号已存在，请使用其他编号");
                }

                // 验证客户名称是否与其他客户重复（排除当前客户）
                var duplicateNameCustomer = await _customerRepository.GetAll()
                    .FirstOrDefaultAsync(c => c.Name == request.Name 
                                             && c.Id != request.Id 
                                             && !c.IsDeleted, cancellationToken);

                if (duplicateNameCustomer != null)
                {
                    _logger.LogWarning("客户名称已存在，ID: {CustomerId}, 名称: {CustomerName}", 
                        request.Id, request.Name);
                    return ApiResult<bool>.Error("客户名称已存在，请使用其他名称");
                }

                // 如果提供了身份证号，验证是否与其他客户重复（排除当前客户）
                if (!string.IsNullOrEmpty(request.IdCard))
                {
                    var duplicateIdCardCustomer = await _customerRepository.GetAll()
                        .FirstOrDefaultAsync(c => c.IdCard == request.IdCard 
                                                 && c.Id != request.Id 
                                                 && !c.IsDeleted, cancellationToken);

                    if (duplicateIdCardCustomer != null)
                    {
                        _logger.LogWarning("身份证号已存在，ID: {CustomerId}, 身份证号: {IdCard}", 
                            request.Id, request.IdCard);
                        return ApiResult<bool>.Error("身份证号已存在，请检查输入");
                    }
                }

                // 如果提供了统一社会信用代码，验证是否与其他客户重复（排除当前客户）
                if (!string.IsNullOrEmpty(request.UnifiedSocialCreditCode))
                {
                    var duplicateCreditCodeCustomer = await _customerRepository.GetAll()
                        .FirstOrDefaultAsync(c => c.UnifiedSocialCreditCode == request.UnifiedSocialCreditCode 
                                                 && c.Id != request.Id 
                                                 && !c.IsDeleted, cancellationToken);

                    if (duplicateCreditCodeCustomer != null)
                    {
                        _logger.LogWarning("统一社会信用代码已存在，ID: {CustomerId}, 代码: {CreditCode}", 
                            request.Id, request.UnifiedSocialCreditCode);
                        return ApiResult<bool>.Error("统一社会信用代码已存在，请检查输入");
                    }
                }

                
                // 更新客户信息
                existingCustomer.CustomerCode = request.CustomerCode;
                existingCustomer.Name = request.Name;
                existingCustomer.Type = request.Type;
                existingCustomer.MnemonicCode = request.MnemonicCode;
                existingCustomer.ContactPersonName = request.ContactPersonName;
                existingCustomer.ContactPersonPhone = request.ContactPersonPhone;
                existingCustomer.IdCard = request.IdCard;
                existingCustomer.UnifiedSocialCreditCode = request.UnifiedSocialCreditCode;
                existingCustomer.Industry = request.Industry;
                existingCustomer.CustomerStage = request.CustomerStage;
                existingCustomer.CustomTags = request.CustomTags;
                existingCustomer.IntendedProduct = request.IntendedProduct;
                existingCustomer.CooperationDate = request.CooperationDate;
                existingCustomer.Remarks = request.Remarks;
                existingCustomer.Province = request.Province;
                existingCustomer.City = request.City;
                existingCustomer.District = request.District;
                existingCustomer.DetailedAddress = request.DetailedAddress;
                existingCustomer.SuperiorCustomerId = request.SuperiorCustomerId;
                existingCustomer.CustomerLevel = request.CustomerLevel;
                existingCustomer.AffiliatedMarket = request.AffiliatedMarket;
                existingCustomer.ServicePersonnel = request.ServicePersonnel;
                existingCustomer.Status = request.Status;
                existingCustomer.IsArchived = request.IsArchived;
                existingCustomer.EntryUnit = request.EntryUnit;
                existingCustomer.UsageUnit = request.UsageUnit;
                existingCustomer.UpdatedTime = DateTime.Now;
                existingCustomer.UpdatedBy = request.UpdatedBy;

                // 执行更新操作
                var result = await _customerRepository.UpdateAsync(existingCustomer);

                if (result > 0)
                {
                    _logger.LogInformation("成功修改客户，ID: {CustomerId}, 名称: {CustomerName}", 
                        request.Id, request.Name);
                    
                    return ApiResult<bool>.Success(true, "客户修改成功");
                }
                else
                {
                    _logger.LogError("修改客户失败，ID: {CustomerId}, 名称: {CustomerName}", 
                        request.Id, request.Name);
                    
                    return ApiResult<bool>.Error("客户修改失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改客户时发生异常，ID: {CustomerId}, 名称: {CustomerName}", 
                    request.Id, request.Name);
                
                return ApiResult<bool>.Error($"修改客户时发生异常: {ex.Message}");
            }
        }
    }
}
